<template>
  <div v-loading="loading" :element-loading-text="loadingText" class="config-edit">
    <div v-show="!showPicDetail">
      <div class="bread-box but20">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item class="btn-green" style=" color: #3DC094;" @click.native="handleBack">成品配置</el-breadcrumb-item>
          <el-breadcrumb-item>成品配置单</el-breadcrumb-item>
        </el-breadcrumb>
        <div>
          <el-button size="mini" @click="handleBack">取消</el-button>
          <el-button type="primary" size="mini" @click="handleSave">保存</el-button>
          <el-button type="primary" size="mini" @click="clickNextStep">提交</el-button>
        </div>
      </div>
      <c-list :column="3">
        <c-list-item label="产品配置单" :value="formData.configCode" />
        <c-list-item label="对应产品配置任务" :value="formData.configTaskCode" />
        <c-list-item label="任务来源" dict-type-code="PRODUCT_CONFIG_TASK_SOURCE" :value="formData.source" />
        <c-list-item label="来源图纸" :value="formData.picTaskCode" />
        <c-list-item label="来源图纸名称" :value="formData.picTaskName" />
        <c-list-item label="产品配置类型" dict-type-code="PRO_CONFIG_TYPE" :value="formData.proConfigType" />
        <c-list-item label="产品配置进度" dict-type-code="PRO_CONFIG_SCHEDULE" :value="formData.schedule" />
        <!-- <c-list-item label="是否含自主配置" dict-type-code="BOOLEANS" :value="formData.haveSelfSampleLoad" /> -->
        <c-list-item label="门店建设项目号" :value="formData.constCode" />
        <c-list-item label="所属门店编码" :value="formData.shopCode" />
        <c-list-item label="所属门店名称" :value="formData.shopName" />
        <c-list-item label="所属客户编码" :value="formData.clientCode" />
        <c-list-item label="所属客户名称" :value="formData.clientName" />
        <c-list-item label="所属办事处" :value="formData.officeName" />
        <c-list-item label="审核结果" dict-type-code="REVIEW_RESULT" :value="formData.reviewResult" />
        <c-list-item label="审核意见" :value="formData.reviewAdvice" />
        <c-list-item label="创建人" :value="formData.createBy" />
        <c-list-item label="创建时间" :value="formData.createTime" />
        <c-list-item label="修改人" :value="formData.lastUpdateBy" />
        <c-list-item label="修改时间" :value="formData.lastUpdateTime" />
      </c-list>
      <!-- <RelevanceDrawing :other-filters="otherFilters" /> -->
      <c-section title="关联图纸信息">
        <c-table-box hide-func :data="formData.designPictureDtos" :table-config="tableConfig" />
      </c-section>
      <c-section title="产品出图明细">
        <el-form ref="rulesForm" :model="formData" label-width="160px">
          <el-row>
            <el-col :span="8">
              <el-form-item label="是否按标准配置上样:" prop="isStandardSample" :rules="[{ required: true, message: '请选择是否按标准配置上样' }]">
                <c-dict-select v-model="formData.isStandardSample" dict-type-code="BOOLEANS" placeholder="是否按标准配置上样" @change="changeSampleLoad" />
              </el-form-item>
            </el-col>
            <el-col v-if="formData.isStandardSample === '0'" :span="8">
              <el-form-item
                label="未按标准配置上样原因:"
                prop="unstandardSampleReason"
                :rules="[{ required: formData.isStandardSample === '0', message: '请选择未按标准配置上样原因' }]"
              >
                <c-dict-select v-model="formData.unstandardSampleReason" dict-type-code="NONSTANDARD_CONFIGURATION" placeholder="未按标准配置上样原因" />
              </el-form-item>
            </el-col>
            <el-col v-if="(formData.isStandardSample === '0' && formData.unstandardSampleReason === 'A')" :span="8">
              <el-form-item
                label="流程申请实例号:"
                prop="processInstanceNo"
                :rules="[{ required: (formData.isStandardSample === '0' && formData.unstandardSampleReason === 'A'), message: '请输入流程申请实例号' },
                         { pattern: /^[a-zA-Z0-9]{1,64}$/, message: '请输入长度在64以内的字母和数字' }]"
              >
                <el-input v-model="formData.processInstanceNo" placeholder="请输入流程申请实例号" />
              </el-form-item>
            </el-col>
            <el-col v-if="(formData.isStandardSample === '0' && formData.unstandardSampleReason === 'B')" :span="8">
              <el-form-item
                label="异常说明:"
                prop="exceptionDesc"
                :rules="[{ required: (formData.unstandardSampleReason === 'B' && formData.isStandardSample === '0'), message: '请输入异常说明' }]"
              >
                <el-input v-model="formData.exceptionDesc" placeholder="请输入异常说明" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="btn-container">
          <span style="color:#E6A23C">已有选择产品【{{ totalProductNum }}】个</span>
          <el-button type="primary" @click="clickRecommend">选择推荐型号</el-button>
          <el-button type="primary" @click="clickMatch">选择搭配型号</el-button>
          <el-button type="primary" @click="clickBat">新增自选产品</el-button>
          <el-button type="primary" @click="clickChangePro">批量选择产品</el-button>
          <el-button type="primary" @click="handleDel">删除</el-button>
        <!-- <el-button type="primary" @click="handleExport">导出</el-button> -->
        </div>
        <div>
          <el-table
            v-loading="tableLoading"
            element-loading-text="加载中"
            :data="outpicCategoryData"
            :span-method="objectSpanMethod"
            border
            max-height="400px"
            :row-class-name="tableRowClassName"
            :header-cell-style="{background:'#F6F6F6', borderRight:'1px solid #EBEEF5'}"
            style="width: 100%; margin: 20px 0"
            @selection-change="selectionChangeHandle"
          >
            <el-table-column type="index" />
            <el-table-column type="selection" width="55" />
            <el-table-column prop="areaName" label="所属区域" min-width="100">
              <template slot-scope="scope">
                <span>{{ scope.row.areaName }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="spaceName" label="所属空间" min-width="150" />
            <el-table-column prop="styleName" label="所属专区" min-width="150" />
            <el-table-column prop="spaceTotalArea" label="空间面积" show-overflow-tooltip min-width="150" />
            <el-table-column prop="seriesName" label="系列名称" min-width="150" />
            <el-table-column prop="categoryNames" label="包含品类" min-width="200" />
            <el-table-column prop="categoryNumber" label="出图品类数量" min-width="150" />
            <el-table-column prop="recommendType" label="推荐类别" show-overflow-tooltip min-width="150">
              <template slot-scope="scope">
                <el-checkbox v-if="scope.row.modelCode" v-model="scope.row.checked" @change="changeChecked(scope.row)" />
                <span>{{ formaterData(recommendTypeList, scope.row.recommendType) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="modelCode" label="型号" min-width="100" />
            <el-table-column prop="recommendProgram" label="所属方案" min-width="150">
              <template slot-scope="scope">
                <span>{{ formaterData(recommendProgramList, scope.row.recommendProgram) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="proPosition" label="产品定位" min-width="150">
              <template slot-scope="scope">
                <span>{{ formaterData(seriesNameList, scope.row.proPosition) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="productName" label="产品" min-width="150">
              <template slot-scope="scope">
                <input-with-dialog
                  v-if="scope.row.modelCode"
                  v-model="scope.row.productArr"
                  :props="{label:'productName',value:'productCode'}"
                  :config="scope.row.productConfig"
                  @change="productChange(scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="productState" label="产品状态" min-width="150">
              <template slot-scope="scope">
                <span>{{ formaterData(proStateList, scope.row.productState) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="pcontrolState" label="采购控制状态" min-width="150">
              <template slot-scope="scope">
                <span>{{ formaterData(canBePurchaseList, scope.row.pcontrolState) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="productNumber" label="数量" min-width="150">
              <template slot-scope="scope">
                <el-input v-if="scope.row.modelCode" v-model="scope.row.productNumber" type="number" size="mini" placeholder="请输入数量" min="1" :max="scope.row.quantity" @change="handelBlur(scope.row)" />
              </template>
            </el-table-column>
          </el-table>
        </div>
      </c-section>
    </div>
    <div>
      <export-files v-if="exportVisible" title="导出" :config="exportConfig" :visible.sync="exportVisible" @success="handleExportSuccess" />
      <recommend v-if="showRecommendDlg" ref="recommend" :visible.sync="showRecommendDlg" :detail-data="recommendData" @success="getRecommendData" />
      <match v-if="showMatchDlg" ref="match" :visible.sync="showMatchDlg" :detail-data="activedMatchData" @success="getMatchData" />
      <bat-select v-if="showBatSelectDlg" ref="match" :visible.sync="showBatSelectDlg" :detail-data="activedProData" @success="getSelfPro" />
      <add-product v-if="showProDlg" ref="proDlg" :visible.sync="showProDlg" :detail-data="selectPro" @success="getModelPro" @goLastPage="goLastPage" />
    </div>
    <detail v-if="showPicDetail" :shop-config-data="rowId" page-flag="shopConfig" :page-show.sync="showPicDetail" @goBack="backDetail" />
  </div>
</template>
<script>
import detail from '../../../shopDrawing/management/detail.vue'
import Match from './match.vue'
import Recommend from './recommend.vue'
import { getProConfigEditData, getProOutpicCategory, queryCategoryData } from '@/api/proConfig'
import { getDictByTypeCode, saveProConfigEditData } from '@/api/proConfig'
import { getDictByPatchType } from '@/api/dataDict'
import BatSelect from './batSelect.vue'
import AddProduct from './addProduct.vue'
import { getAreaData } from '../../task/components/index'
export default {
  name: 'PCFinishedConfigEdit',
  components: {
    // RelevanceDrawing,
    Recommend,
    Match,
    BatSelect,
    AddProduct,
    detail
  },
  data() {
    return {
      rowId: '',
      showPicDetail: false,
      loading: false,
      loadingText: '',
      exportVisible: false,
      tableLoading: false,
      showRecommendDlg: false,
      showMatchDlg: false,
      showBatSelectDlg: false,
      showProDlg: false,
      areaList: [],
      detailTableFilters: [],
      recommendProgramList: [],
      seriesNameList: [],
      belongRegionList: [],
      canBePurchaseList: [],
      designRangeList: [],
      decorationTypeList: [],
      designBizTypeList: [],
      recommendTypeList: [],
      proStateList: [],
      recommendData: {},
      activedMatchData: {},
      activedProData: {},
      selectPro: {},
      regionList: [
        { dictCode: 'Q001', dictName: '成品' },
        { dictCode: 'Q002', dictName: '全屋定制' },
        { dictCode: 'Q003', dictName: '整体橱柜' },
        { dictCode: 'Q004', dictName: '卫浴' },
        { dictCode: 'Q005', dictName: '样板间' }
      ],
      formData: {
        designPictureDtos: []
      },
      formRules: {
        haveSelfSampleLoad: [{ required: true, message: '请选择是否含自主上样' }]
      },
      outpicCategoryData: [],
      otherFilters: [],
      tableSelected: [],
      tableConfig: {
        setting: [
          {
            prop: 'picTaskCode',
            label: '图纸编码',
            minWidth: 100,
            className: 'btn-green',
            isButton: true,
            clickFun: this.toPicDetail
          },
          {
            prop: 'picType',
            label: '图纸类型',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'PIC_TYPE'
            },
            minWidth: 100
          },
          {
            prop: 'designRange',
            label: '设计范围',
            minWidth: 100,
            render: (creat, row) => {
              if (!row.designRange) {
                return
              }
              let list = []
              if (typeof (row.designRange) === 'string') {
                list = row.designRange.split(',')
              } else {
                list = row.designRange
              }
              const arr = []
              this.designRangeList.forEach((item) => {
                const flag = list.some(v => v === item.dictCode)
                if (flag) {
                  arr.push(item.dictName)
                }
              })
              return (<span>{ arr.toString() }</span>)
            }
          },
          {
            prop: 'decorationType',
            label: '装修形式',
            minWidth: 100,
            render: (creat, row) => {
              if (!row.decorationType) {
                return
              }
              let list = []
              if (typeof (row.decorationType) === 'string') {
                list = row.decorationType.split(',')
              } else {
                list = row.decorationType
              }
              const arr = []
              this.decorationTypeList.forEach((item) => {
                const flag = list.some(v => v === item.dictCode)
                if (flag) {
                  arr.push(item.dictName)
                }
              })
              return (<span>{ arr.toString() }</span>)
            }
          },
          {
            prop: 'designSpace',
            label: '设计区域',
            minWidth: 100,
            render: (creat, row) => {
              if (!row.designSpace) {
                return
              }
              let list = []
              if (typeof (row.designSpace) === 'string') {
                list = row.designSpace.split(',')
              } else {
                list = row.designSpace
              }
              const arr = []
              this.areaList.forEach((item) => {
                const flag = list.some(v => v === item.dictCode)
                if (flag) {
                  arr.push(item.dictName)
                }
              })
              return (<span>{ arr.toString() }</span>)
            }
          },
          {
            prop: 'designBizType',
            label: '设计业务类型',
            minWidth: 140,
            render: (creat, row) => {
              if (!row.designBizType) {
                return
              }
              let list = []
              if (typeof (row.designBizType) === 'string') {
                list = row.designBizType.split(',')
              } else {
                list = row.designBizType
              }
              const arr = []
              this.designBizTypeList.forEach((item) => {
                const flag = list.some(v => v === item.dictCode)
                if (flag) {
                  arr.push(item.dictName)
                }
              })
              return (<span>{ arr.toString() }</span>)
            }
          },
          {
            prop: 'picTotalArea',
            label: '设计总面积',
            minWidth: 120
          },
          {
            prop: 'softwareSumArea',
            label: '软体区面积',
            minWidth: 120
          },
          {
            prop: 'suiteSumArea',
            label: '套房区面积',
            minWidth: 120
          },
          // {
          //   prop: 'finishedProductAreaSummary',
          //   label: '成品业务面积汇总',
          //   minWidth: 100
          // },
          {
            prop: 'haveEAndC',
            label: '是否含成融定',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'BOOLEANS'
            },
            minWidth: 140
          },
          {
            prop: 'eandCArea',
            label: '成融定面积',
            minWidth: 120
          },
          {
            prop: 'newBusinessAreaSummary',
            label: '新业务面积汇总',
            minWidth: 100
          },
          {
            prop: 'expectEndTime',
            label: '预计设计完成时间',
            minWidth: 140
          },
          {
            prop: 'designUnitName',
            label: '设计单位',
            minWidth: 100
          },
          {
            prop: 'designerName',
            label: '设计师',
            minWidth: 100
          },
          {
            prop: 'schedule',
            label: '图纸进度',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'PIC_DESIGN_SCHEDULE'
            },
            minWidth: 100
          },
          {
            prop: 'state',
            label: '图纸状态',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'PIC_DESIGN_STATE'
            },
            minWidth: 100
          }
        ]
      }
    }
  },
  computed: {
    totalProductNum() {
      const temp = this.outpicCategoryData.filter(v => v.modelCode)
      return temp.length
    },
    exportConfig() {
      return [{
        code: 'export',
        name: '成品类样品配置产品出图明细',
        dataApi: '/slm-admin/api/v1/designOutpicDetailTask/exportCategoryNumberPageByPicTaskCode?type=0',
        // selectedRows: this.tableSelected,
        paramsRaw: {},
        filtersRaw: this.detailTableFilters,
        queryField: 'id'
      }]
    }
  },
  async created() {
    this.loading = true
    this.loadingText = '加载中'
    await this.getDictByPatchTypeAll(['PRODUCT_STATE', 'CAN_BE_PURCHASE']).then(res => {
      this.proStateList = res.PRODUCT_STATE
      this.canBePurchaseList = res.CAN_BE_PURCHASE
    }).catch(() => {
      this.loading = false
      this.loadingText = ''
    })
    await this.getDictByTypeCode(['RECOMMEND_TYPE', 'RECOMMEND_PROGRAM', 'SERIES_NAME', 'BELONG_REGION', 'DECORATION_RANGE',
      'DECORATION_FORM', 'BIZ_TYPE']).then(res => {
      this.recommendTypeList = res.RECOMMEND_TYPE
      this.recommendProgramList = res.RECOMMEND_PROGRAM
      this.seriesNameList = res.SERIES_NAME
      this.belongRegionList = res.BELONG_REGION
      this.designRangeList = res.DECORATION_RANGE // 设计范围
      this.decorationTypeList = res.DECORATION_FORM // 装修形式
      this.designBizTypeList = res.BIZ_TYPE // 设计业务类型
    }).catch(() => {
      this.loading = false
      this.loadingText = ''
    })
    this.areaList = await getAreaData()
    this.formData.id = this.$route.params.id
    getProConfigEditData(this.formData.id).then(async res => {
      if (res.success && res.data) {
        this.formData = res.data
        this.allOutpicTableData = this.formData.configOutPicDtos || []
        if (this.allOutpicTableData.length) {
          this.allOutpicTableData.forEach(item => {
            // item.outpicCategoryNumberId = item.id
            item.checked = false
          })
        }
        this.outpicCategoryData = await this.tableFormater(this.allOutpicTableData)
        if (this.formData.designPictureDtos.length && !this.outpicCategoryData.length) {
          await this.getOutpicCategory(this.formData.designPictureDtos)
        }
        this.detailTableFilters = [{ 'id': 'configSheetId', 'property': 'configSheetId', 'operator': '=', 'value': this.formData.id }]
        // const tmp111 = await this.resDataFormater(this.outpicCategoryData)
      }
      this.loading = false
    }).catch(() => {
      this.loading = false
      this.loadingText = ''
    })
  },
  methods: {
    /**
     * 表格合并
     * @param {*} param0
     * row 表格每一行的数据
     * column 表格每一列的数据
     * rowIndex 表格的行索引,不包括表头,从0开始
     * columnIndex 表格的列索引,从0开始
     */
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex <= 5) {
        // 过滤需要合并的行数
        if (row.spanIndex) {
          // 若rowIndex存在，则合并
          return {
            rowspan: row.spanIndex,
            colspan: 1
          }
        } else {
          return {
            rowspan: 0,
            colspan: 0
          }
        }
      }
    },
    // 设置表格多选行高亮
    tableRowClassName({ row, rowIndex }) {
      const filterArr = this.tableSelected.filter(item =>
        row.areaCode === item.areaCode &&
        row.spaceTotalArea === item.spaceTotalArea &&
        row.spaceCode === item.spaceCode &&
        row.categoryCodes === item.categoryCodes &&
        row.seriesCode === item.seriesCode &&
        row.styleCode === item.styleCode)
      const arr = this.outpicCategoryData.filter(item => item.checked &&
      row.areaCode === item.areaCode &&
        row.spaceTotalArea === item.spaceTotalArea &&
        row.spaceCode === item.spaceCode &&
        row.categoryCodes === item.categoryCodes &&
        row.seriesCode === item.seriesCode &&
        row.styleCode === item.styleCode)
      return (filterArr.length > 0 || arr.length > 0) ? 'selected-highlight' : ''
    },
    selectionChangeHandle(rows) {
      this.tableSelected = rows
    },
    removeEqualData(arr) {
      const newArr = []
      for (var i = 0; i < arr.length; i++) {
        if (!newArr.includes(arr[i])) {
          newArr.push(arr[i])
        }
      }
      return newArr
    },
    // 获取品类
    async getCategoryData(arr, flag) {
      const codes = '[' + arr.join(',') + ']'
      let filterRow = []
      if (flag === 'A') {
        filterRow = [{ 'id': 'code', 'property': 'code', 'operator': 'in', 'value': codes }]
      } else if (flag === 'B') {
        filterRow = [{ 'id': 'parentCode', 'property': 'parentCode', 'operator': 'in', 'value': codes }]
      }
      const dataForm = new FormData()
      dataForm.append('pageFlag', false)
      dataForm.append('filtersRaw', JSON.stringify(filterRow))
      let list = []
      await queryCategoryData(dataForm).then(res => {
        if (res.success) {
          if (flag === 'A') {
            list = res.data.records
          } else {
            list = res.data.records
          }
        }
      })
      return list
    },
    // 获取末级品类
    async getfinalLevel(arr) {
      const plCodesArr = arr.map(item => item.categoryCodes)
      const plCodes = this.removeEqualData(plCodesArr)
      const plDataArr = await this.getCategoryData(plCodes, 'A')
      const unFinalLevel = plDataArr.filter(item => item.isFinalLevel === '0')
      const finalLevel = plDataArr.filter(item => item.isFinalLevel === '1')
      const unFinalPlArr = unFinalLevel.map(item => item.code)
      const plfinaArr = await this.getCategoryData(unFinalPlArr, 'B')
      const categoryArr = [...finalLevel, ...plfinaArr]
      arr.forEach(row => {
        const codeArr = []
        // row.childCategory = []
        categoryArr.forEach(item => {
          if (item.parentCode && item.parentCode === row.categoryCodes) {
            codeArr.push(item.code)
          } else if (!item.parentCode && item.code === row.categoryCodes) {
            codeArr.push(item.code)
          }
          row.childCategory = '[' + codeArr.join(',') + ']'
        })
      })
    },
    // async resDataFormater(data) {
    //   if (!data || !data.length) return []
    //   const t = {}
    //   for (const item of data) {
    //     const key = item.areaCode
    //     if (t[key] === undefined) {
    //       t[key] = []
    //     }
    //     t[key].push(item)
    //   }
    //   // 按照区域合并
    //   const result = []
    //   for (const [k, v] of Object.entries(t)) {
    //     const programs = {}
    //     for (let i = 0; i < v.length; i++) {
    //       const item = v[i]
    //       const key = item.spaceCode || item.spaceName
    //       if (programs[key] === undefined) {
    //         programs[key] = []
    //       }
    //       programs[key].push(item)
    //     }
    //     // 按照方案合并
    //     // eslint-disable-next-line no-unused-vars
    //     const obj = {}
    //     for (const [k, v] of Object.entries(programs)) {
    //       v.forEach((e, i) => {
    //         const key = e.styleCode || e.styleName
    //         if (obj[key] === undefined) {
    //           obj[key] = []
    //         }
    //         obj[key].push(e)
    //       })
    //     }
    //     for (const [I, item] of Object.entries(obj)) {
    //       const obj1 = {}
    //       item.forEach((e, i) => {
    //         const key1 = e.categoryCodes || e.categoryNames
    //         if (obj1[key1] === undefined) {
    //           obj1[key1] = []
    //         }
    //         obj1[key1].push(e)
    //       })
    //       for (const [k1, Pitem] of Object.entries(obj1)) {
    //         Pitem.forEach((e, i) => {
    //           if (i === 0) {
    //             e.categorySpanRow = Pitem.length
    //             e.categorySpanColumn = 1
    //           } else {
    //             e.categorySpanRow = 0
    //             e.categorySpanColumn = 0
    //           }
    //           e.configDetailDtos = []
    //           const prodObj = {
    //             checked: false,
    //             modelCode: e.modelCode,
    //             recommendType: e.recommendType,
    //             recommendProgram: e.recommendProgram,
    //             proPosition: e.proPosition,
    //             productDesc: e.productDesc,
    //             productCode: e.productCode,
    //             productState: e.productState,
    //             pcontrolState: e.pcontrolState,
    //             productNumber: e.productNumber
    //           }
    //           e.configDetailDtos.push(prodObj)
    //           result.push(e)
    //         })
    //       }
    //     }
    //     // }
    //   }
    //   return result
    // },
    async tableFormater(data) {
      if (!data || !data.length) return []
      const arr = []
      data.forEach(row => {
        if (row.configDetailDtos && row.configDetailDtos.length) {
          row.configDetailDtos.forEach((item, index) => {
            item.outpicCategoryNumberId = row.id || row.outpicCategoryNumberId
            item.areaCode = row.areaCode
            item.areaName = row.areaName
            item.spaceName = row.spaceName
            item.spaceCode = row.spaceCode
            item.spaceTotalArea = row.spaceTotalArea
            item.styleName = row.styleName
            item.styleCode = row.styleCode
            item.categoryName = row.categoryNames
            item.categoryCode = row.categoryCodes
            item.categoryNames = row.categoryNames
            item.categoryCodes = row.categoryCodes
            item.categoryNumber = row.categoryNumber
            if (row.seriesCode) {
              item.seriesName = row.seriesName
              item.seriesCode = row.seriesCode
            } else {
              row.seriesName = item.seriesName
              row.seriesCode = item.seriesCode
            }
            // item.checked = false

            if (index === 0) {
              item.spanIndex = row.configDetailDtos.length
            }
            this.$set(item, 'checked', false)
            arr.push(item)
          })
        } else {
          row.outpicCategoryNumberId = row.id || row.outpicCategoryNumberId
          row.recommendType = ''
          row.modelCode = ''
          row.modelName = ''
          row.proPosition = ''
          row.productDesc = ''
          row.productCode = ''
          row.productArr = []
          row.productState = ''
          row.pcontrolState = ''
          row.productNumber = ''
          // row.checked = false
          this.$set(row, 'checked', false)
          row.spanIndex = 1
          arr.push(row)
        }
      })
      await this.getfinalLevel(arr)
      const tmpArr = JSON.parse(JSON.stringify(arr))
      tmpArr.forEach(item => {
        const productArr = [{ label: item.productDesc, value: item.productCode }]
        this.$set(item, 'productArr', productArr)
        this.$set(item, 'checked', false)
        const productConfig = {
          title: '产品',
          interfacePath: `/select-service/api/v1/productInfo/page`,
          setting: [{ prop: 'productCode', title: '编码' },
            { prop: 'productName', title: '名称' }],
          filtersRaw: [{ 'id': 'proState', 'property': 'proState', 'operator': '=', 'value': 'E' },
            { 'id': 'prodModelCode', 'property': 'prodModelCode', 'operator': '=', 'value': item.modelCode },
            { 'id': 'productCategoryCode', 'property': 'productCategoryCode', 'operator': 'in', 'value': item.childCategory }]
        }
        this.$set(item, 'productConfig', productConfig)
      })
      return tmpArr
    },
    // 获取数据字典
    async getDictByPatchTypeAll(data) {
      const obj = await getDictByTypeCode(data)
        .then(res => {
          return res
        })
      return obj
    },
    // 获取数据字典
    async getDictByTypeCode(data) {
      const obj = await getDictByPatchType(data)
        .then(res => {
          return res
        })
      return obj
    },
    // 格式化数据
    formaterData(arr, dictCode) {
      if (!arr || !arr.length) return
      const tmpArr = arr.filter(item => item.dictCode === dictCode)
      if (tmpArr.length) {
        return tmpArr[0].dictName
      }
      return dictCode
    },
    // 获取出图品类及数量
    getOutpicCategory() {
      this.tableLoading = true
      const picTaskCodes = this.formData.designPictureDtos.map(item => item.picTaskCode)
      getProOutpicCategory(picTaskCodes).then(async res => {
        if (res.success && res.data && res.data.records) {
          this.allOutpicTableData = res.data.records
          this.allOutpicTableData.forEach(item => {
            item.configDetailDtos = []
            item.spanIndex = 1
            item.outpicCategoryNumberId = item.id
          })
          this.outpicCategoryData = await this.tableFormater(res.data.records)
        }
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    // 查看图纸详情
    toPicDetail(row) {
      this.rowId = row
      this.showPicDetail = true
    },
    // 返回配置详情
    backDetail() {
      this.showPicDetail = false
    },
    // 选择是否自主上样
    changeSampleLoad(value) {
      this.$set(this.formData, 'unstandardSampleReason', '')
      this.$set(this.formData, 'processInstanceNo', '')
      this.$set(this.formData, 'exceptionDesc', '')
      // this.formData.processInstanceNo = ''
      // this.formData.exceptionDesc = ''
      this.$nextTick(() => {
        this.$refs.rulesForm.clearValidate()
      })
    },
    // 修改数量
    handelBlur(row) {
      const num = Number(row.productNumber)
      if (isNaN(num) || num < 1 || (num % 1 !== 0)) {
        row.productNumber = 1
        this.$message.warning('请输入正整数')
      }
      this.allOutpicTableData.forEach(item => {
        if (row.areaCode === item.areaCode &&
        row.spaceTotalArea === item.spaceTotalArea &&
        row.spaceCode === item.spaceCode &&
        row.categoryCodes === item.categoryCodes &&
        row.seriesCode === item.seriesCode &&
        row.styleCode === item.styleCode) {
          if (item.configDetailDtos && item.configDetailDtos.length) {
            item.configDetailDtos.forEach(c => {
              if (c.modelCode === row.modelCode && c.productCode === row.productCode) {
                c.productNumber = row.productNumber
              }
            })
          }
        }
      })
    },
    // 选择推荐型号
    clickRecommend(data) {
      // console.log('产品回推荐', this.tableSelected)
      if (!this.tableSelected.length) {
        this.$message.warning('请至少选择一条品类数据')
        return
      }
      // return
      const arr = this.outpicCategoryData.filter(item => {
        const index = this.tableSelected.findIndex(row =>
          row.areaCode === item.areaCode &&
        row.spaceTotalArea === item.spaceTotalArea &&
        row.spaceCode === item.spaceCode &&
        row.categoryCodes === item.categoryCodes &&
        row.seriesCode === item.seriesCode &&
        row.styleCode === item.styleCode)
        return index !== -1
      })
      this.recommendData.otherFilter = arr
      if (data) {
        this.recommendData.lastSelected = data.lastSelected
      }
      this.recommendData.constCode = this.formData.constCode
      this.showRecommendDlg = true
    },
    // 选择自选产品
    clickBat() {
      // if (!this.tableSelected.length) {
      //   this.$message.warning('请至少选择一条品类数据')
      //   return
      // }
      // const arr = this.outpicCategoryData.filter(item => {
      //   const index = this.tableSelected.findIndex(row =>
      //     row.belongRegion === item.belongRegion &&
      //   row.spaceTotalArea === item.spaceTotalArea &&
      //   row.spaceCode === item.spaceCode &&
      //   row.categoryCodes === item.categoryCodes &&
      //   row.seriesCode === item.seriesCode &&
      //   row.styleCode === item.styleCode)
      //   return index !== -1
      // })
      // return
      this.activedProData.otherFilter = this.outpicCategoryData.filter(item => item.modelCode)
      this.showBatSelectDlg = true
    },
    // 选择搭配型号
    clickMatch(data) {
      if (!this.tableSelected.length) {
        this.$message.warning('请至少选择一条品类数据')
        return
      }
      //  &&
      // row.categoryCodes === item.categoryCodes &&
      // row.seriesCode === item.seriesCode &&
      // row.styleCode === item.styleCode
      // row.spaceTotalArea === item.spaceTotalArea &&
      const arr = this.allOutpicTableData.filter(item => {
        const index = this.tableSelected.findIndex(row =>
          row.areaCode === item.areaCode &&
        row.spaceCode === item.spaceCode)
        return index !== -1
      })
      // console.log('搭配的推荐数据', arr)
      const flagArr = []
      if (arr.length) {
        arr.forEach(row => {
          const hasRecommend = row.configDetailDtos.some(item => item.recommendType === 'RECOMMEND')
          if (!hasRecommend) {
            flagArr.push('false')
          } else {
            flagArr.push('true')
          }
        })
      }
      if (!flagArr.some(item => item === 'true')) {
        this.$message.warning('勾选的出图明细数据中不存在推荐类型为【推荐产品】的数据，请先选择推荐型号')
        return
      }
      const arr1 = this.outpicCategoryData.filter(item => {
        const index = this.tableSelected.findIndex(row =>
          row.areaCode === item.areaCode &&
        row.spaceCode === item.spaceCode)
        return index !== -1
      })
      this.activedMatchData.otherFilter = arr1
      if (data) {
        this.activedMatchData.lastSelected = data.lastSelected
      }
      this.activedMatchData.constCode = this.formData.constCode
      this.showMatchDlg = true
    },
    // 批量选择产品
    clickChangePro() {
      const arr = this.outpicCategoryData.filter(item => item.checked)
      if (!arr.length) {
        this.$message.warning('请至少选择一条型号数据')
        return
      }
      this.selectPro.otherFilter = arr
      this.selectPro.type = 'change'
      this.showProDlg = true
    },
    // 获取推荐型号数据
    getRecommendData(data) {
      const arr = []
      data.data.forEach(row => {
        row.configDetailDtos.forEach(item => {
          item.outpicCategoryNumberId = row.outpicCategoryNumberId
          item.areaCode = row.areaCode
          item.spaceCode = row.spaceCode
          item.spaceTotalArea = row.spaceTotalArea
          item.seriesCode = row.seriesCode
          item.styleCode = row.styleCode
          item.categoryCodes = row.categoryCode
          arr.push(item)
        })
      })
      // return
      this.selectPro.otherFilter = arr
      this.selectPro.lastSelected = data.lastSelected
      this.selectPro.type = 'recommend'
      this.showProDlg = true
    },
    // 获取搭配推荐型号数据
    getMatchData(data) {
      const arr = []
      data.data.forEach(row => {
        row.configDetailDtos.forEach(item => {
          item.outpicCategoryNumberId = row.outpicCategoryNumberId
          item.areaCode = row.areaCode
          item.areaName = row.areaName
          item.spaceCode = row.spaceCode
          item.spaceName = row.spaceName
          item.spaceTotalArea = row.spaceTotalArea
          item.seriesCode = row.seriesCode
          item.styleCode = row.styleCode
          item.categoryCodes = row.categoryCodes
          arr.push(item)
        })
      })
      const arr1 = this.unique(arr, 'modelCode')
      this.selectPro.otherFilter = arr1
      this.selectPro.lastSelected = data.lastSelected
      this.selectPro.type = 'match'
      this.showProDlg = true
    },
    // 获取产品
    async getModelPro(data) {
      const arr = []
      data.dataList.forEach(item => {
        this.allOutpicTableData.forEach(row => {
          let plCode = ''
          let xlCode = ''
          let fgCode = ''
          if (data.type === 'match') {
            plCode = item.detailCategoryCode
            xlCode = item.detailSeriesCode
            fgCode = item.detailStyleCode
          } else {
            plCode = item.categoryCodes
            xlCode = item.seriesCode
            fgCode = item.styleCode
          }
          if (row.areaCode === item.areaCode &&
        row.spaceCode === item.spaceCode &&
        row.categoryCodes === plCode &&
        row.seriesCode === xlCode &&
        row.styleCode === fgCode) {
            if (data.type !== 'change') {
              row.configDetailDtos = [...row.configDetailDtos, ...item.configDetailDtos]
            } else {
              row.configDetailDtos.forEach(rItem => {
                item.configDetailDtos.forEach(dItem => {
                  if (rItem.modelCode === dItem.modelCode) {
                    rItem.productCode = dItem.productCode
                    rItem.productDesc = dItem.productDesc
                    rItem.productState = dItem.productState
                    rItem.pcontrolState = dItem.pcontrolState
                    rItem.detailCategoryCode = dItem.detailCategoryCode || ''
                  }
                })
              })
            }
          } else {
            if (data.type === 'match') {
              const obj = {
                areaCode: item.areaCode,
                areaName: item.areaName,
                spaceName: item.spaceName,
                spaceCode: item.spaceCode,
                styleCode: item.detailStyleCode,
                styleName: item.detailStyleName,
                seriesCode: item.detailSeriesCode,
                seriesName: item.detailSeriesName,
                categoryCodes: item.detailCategoryCode,
                categoryNames: item.detailCategoryName,
                configDetailDtos: item.configDetailDtos
              }
              // obj.configDetailDtos.push(item)
              if (!arr.length) {
                arr.push(obj)
              } else {
                const flag = arr.some(a => a.styleCode === fgCode &&
                a.seriesCode === item.xlCode &&
                a.categoryCodes === item.plCode)
                if (flag) {
                  arr.forEach(a => {
                    if (a.styleCode === fgCode &&
                a.seriesCode === xlCode &&
                a.categoryCodes === plCode) {
                      a.configDetailDtos = [...a.configDetailDtos, ...item.configDetailDtos]
                    }
                  })
                } else {
                  arr.push(obj)
                }
              }
            }
          }
        })
      })
      arr.forEach(item => {
        item.configDetailDtos = this.unique(item.configDetailDtos, 'productCode')
      })
      const arr1 = this.unique(arr, 'spaceCode')
      this.allOutpicTableData = [...arr1, ...this.allOutpicTableData]
      // console.log('获取产品后', this.allOutpicTableData)
      // return
      this.outpicCategoryData = await this.tableFormater(this.allOutpicTableData)
    },
    // 去重
    unique(arr, flag) {
      const res = new Map()
      return arr.filter((arr) => !res.has(arr[flag]) && res.set(arr[flag], 1))
    },
    // 获取自选产品
    async getSelfPro(data) {
      // console.log('获取自选产品111', data)
      // return
      // const arr = []
      const tmpTableData = JSON.parse(JSON.stringify(this.allOutpicTableData))
      const haveCategoryArr = tmpTableData.filter(item => {
        const index = data.findIndex(row => row.categoryCodes === item.categoryCodes &&
        row.seriesCode === item.seriesCode &&
        row.styleCode === item.styleCode)
        return index !== -1
      })
      const notCategoryArr = data.filter(item => {
        const index = tmpTableData.findIndex(row => row.categoryCodes === item.categoryCodes &&
        row.seriesCode === item.seriesCode &&
        row.styleCode === item.styleCode)
        return index === -1
      })
      // const unEqualArr = tmpTableData.filter(item => {
      //   const index = data.findIndex(row => row.categoryCodes === item.categoryCodes &&
      //   row.seriesCode === item.seriesCode &&
      //   row.styleCode === item.styleCode)
      //   return index === -1
      // })
      // return
      if (haveCategoryArr.length) {
        this.allOutpicTableData.forEach(item => {
          data.forEach(row => {
            if (row.categoryCodes === item.categoryCodes &&
        row.seriesCode === item.seriesCode &&
        row.styleCode === item.styleCode) {
              row.recommendType = 'EXIST_OPTIONAL'
              if (!item.configDetailDtos || !item.configDetailDtos.length || item.configDetailDtos.some(v => v.recommendType === 'NEW_OPTIONAL')) {
                row.recommendType = 'NEW_OPTIONAL'
              }
              if (!item.configDetailDtos) {
                item.configDetailDtos = []
                item.configDetailDtos.push(item)
              } else if (item.configDetailDtos) {
                // item.configDetailDtos = [...item.configDetailDtos, ...row]
                item.configDetailDtos.push(row)
              }
            }
          })
        })
      }
      const arr = []
      if (notCategoryArr.length) {
        notCategoryArr.forEach(item => {
          item.recommendType = 'NEW_OPTIONAL'
          const obj = {
            styleCode: item.styleCode,
            styleName: item.styleName,
            seriesCode: item.seriesCode,
            seriesName: item.seriesName,
            categoryCodes: item.categoryCodes,
            categoryNames: item.categoryNames,
            configDetailDtos: []
          }
          obj.configDetailDtos.push(item)
          if (!arr.length) {
            arr.push(obj)
          } else {
            const flag = arr.some(a => a.styleCode === item.styleCode &&
                a.seriesCode === item.seriesCode &&
                a.categoryCodes === item.categoryCodes)
            if (flag) {
              arr.forEach(a => {
                if (a.styleCode === item.styleCode &&
                a.seriesCode === item.seriesCode &&
                a.categoryCodes === item.categoryCodes) {
                  a.configDetailDtos.push(item)
                }
              })
            } else {
              arr.push(obj)
            }
          }
        })
        arr.forEach(item => {
          item.configDetailDtos = this.unique(item.configDetailDtos, 'productCode')
        })
      }
      // this.allOutpicTableData = [...arr, ...haveCategoryArr, ...unEqualArr]
      this.allOutpicTableData = [...arr, ...this.allOutpicTableData]
      // console.log('自选产品arr', this.allOutpicTableData)
      this.outpicCategoryData = await this.tableFormater(this.allOutpicTableData)
    },
    // 更换产品
    productChange(row) {
      if (row.productArr.length) {
        row.productCode = row.productArr[0].productCode
        row.productDesc = row.productArr[0].productName
        row.productState = row.productArr[0].proState
        row.pcontrolState = row.productArr[0].canBePurchase
      }
    },
    goLastPage(data) {
      if (data.flag === 'recommend') {
        console.log('返回推荐型号', data)
        this.clickRecommend(data)
      } else if (data.flag === 'match') {
        this.clickMatch(data)
      }
    },
    // 删除
    handleDel() {
      const checkedArr = this.outpicCategoryData.filter(item => item.checked)
      if (!checkedArr.length && !this.tableSelected.length) {
        this.$message.warning('请选择【删除】项')
        return
      }
      const selfArr = this.tableSelected.filter(item => !item.spaceTotalArea)
      let unselfArr = []
      if (this.tableSelected.length) {
        unselfArr = this.tableSelected.filter(item => item.spaceTotalArea)
        if (unselfArr.length) {
          this.$message.warning('当前勾选删项包含不可删除数据，请重新选择')
          return
        }
      }
      let tip = '是否确认删除?'
      if (checkedArr.length) {
        const hasRecommend = checkedArr.filter(item => item.recommendType === 'RECOMMEND')
        if (hasRecommend.length) {
          tip = '当有搭配产品存在时，删除推荐产品可能会影响搭配产品展示效果，是否确认删除？'
        }
      }
      this.$confirm(tip, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        let delArr = []
        if (selfArr.length) {
          delArr = await this.allOutpicTableData.filter(row => {
            const index = selfArr.findIndex(item => row.areaCode === item.areaCode &&
        row.spaceTotalArea === item.spaceTotalArea &&
        row.spaceCode === item.spaceCode &&
        row.categoryCodes === item.categoryCodes &&
        row.seriesCode === item.seriesCode &&
        row.styleCode === item.styleCode)
            return index === -1
          })
        } else {
          delArr = JSON.parse(JSON.stringify(this.allOutpicTableData))
        }
        if (checkedArr.length) {
          delArr.forEach(row => {
            if (row.configDetailDtos && row.configDetailDtos.length) {
              const arr = row.configDetailDtos.filter(item => !item.checked)
              row.configDetailDtos = [...arr]
            }
          })
        }
        this.allOutpicTableData = [...delArr]
        this.outpicCategoryData = await this.tableFormater(this.allOutpicTableData)
      })
    },
    // 导出
    handleExport() {
      this.exportVisible = true
    },
    // 取消
    handleBack() {
      this.$store.dispatch('views/goBack')
    },
    // 保存
    handleSave() {
      this.loading = true
      this.loadingText = '系统处理中'
      const picIds = this.formData.designPictureDtos.map(item => item.id)
      this.formData.picIds = picIds
      // this.formData.productConfigDetailDtos = this.outpicCategoryData
      this.formData.productConfigOutpicDtos = this.allOutpicTableData
      saveProConfigEditData(this.formData).then(res => {
        if (res.success) {
          this.$message.success('操作成功')
          this.handleBack()
        }
        this.loading = false
        this.loadingText = ''
      }).catch(() => {
        this.loading = false
        this.loadingText = ''
      })
    },
    // 提交
    clickNextStep() {
      // isSatisfyOutpicNum  是否满足出图品类要求
      this.$refs.rulesForm.validate(validate => {
        if (validate) {
          const flag = this.allOutpicTableData.some(item => !item.configDetailDtos || !item.configDetailDtos.length)
          const flag2 = this.outpicCategoryData.some(item => (item.modelCode && !item.productCode) || (item.modelCode && !item.productCode.length))
          const flag3 = this.outpicCategoryData.some(item => !item.modelCode)
          if (flag2) {
            this.$message.warning('请完善产品出图明细')
            return
          }
          if ((flag && this.formData.isStandardSample === '1') || (flag3 && this.formData.isStandardSample === '1')) {
            this.$message.warning('您所选配置产品总量不满足出图品类总量要求, 请完善产品出图明细')
            return
          }
          this.allOutpicTableData.forEach(row => {
            let proAllNum = 0
            row.configDetailDtos.forEach(item => {
              if (!item.productNumber) {
                item.productNumber = 0
              }
              proAllNum = proAllNum + Number(item.productNumber)
            })
            row.proAllNum = proAllNum
          })
          const arr = this.allOutpicTableData.filter(row => row.proAllNum < row.categoryNumber)
          if (this.formData.isStandardSample === '0' && arr.length) {
            this.$confirm('您所选配置产品总量不满足出图品类总量要求，请确认是否符合自主上样要求?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              const isSatisfyOutpicNum = 0
              // return
              this.submitData(isSatisfyOutpicNum)
            })
          } else if ((this.formData.isStandardSample === '0' && !arr.length) || (this.formData.isStandardSample === '1' && !arr.length)) {
            const isSatisfyOutpicNum = 1
            // return
            this.submitData(isSatisfyOutpicNum)
          } else if (this.formData.isStandardSample === '1' && arr.length) {
            this.$message.warning('您所选配置产品总量不满足出图品类总量要求，无法提交')
          }
        }
      })
    },
    submitData(isSatisfyOutpicNum) {
      this.loading = true
      this.loadingText = '系统处理中'
      const picIds = this.formData.designPictureDtos.map(item => item.id)
      this.formData.picIds = picIds
      // this.formData.productConfigDetailDtos = this.outpicCategoryData
      this.formData.productConfigOutpicDtos = this.allOutpicTableData
      this.formData.isSatisfyOutpicNum = isSatisfyOutpicNum
      this.formData.schedule = 'B'
      saveProConfigEditData(this.formData).then(res => {
        if (res.success) {
          this.$message.success('操作成功')
          this.handleBack()
        }
        this.loading = false
        this.loadingText = ''
      }).catch(() => {
        this.loading = false
        this.loadingText = ''
      })
    },
    changeChecked(row) {
      this.allOutpicTableData.forEach(item => {
        item.configDetailDtos.forEach(detailItem => {
          if (detailItem.modelCode === row.modelCode) {
            detailItem.checked = row.checked
          }
        })
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.but20{ margin-bottom: 20px;}
.el-breadcrumb__inner .btn-green{
    color: #3DC094;
}
/deep/.el-breadcrumb__inner{
  color: $qup-color-primary;
}
</style>
